import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.filesystem.File;
import mx.controls.Alert;
import mx.core.Application;
import mx.messaging.messages.HTTPRequestMessage;
import flash.utils.Timer;
import flash.events.TimerEvent;


[Bindable]
public var usernamestr:String;
public var passstr:String;
public var AIRScrobblerVersion:String="1.0";

public function init():void{
	loadSettings();
	lastfmurl.label='http://www.last.fm/user/'+username.text;
	usernamestr=username.text;
	passstr=password.text;
}


public var slines:Array=new Array();
public var fix:String;
public var savepass:String;
public var exitapp:String;
public var dellog:String;
public function loadSettings():void{
	var settings:Array = new Array();
	var mySettings:File = File.applicationDirectory;
	mySettings = mySettings.resolvePath("LogScrobbler.txt"); // Point it to an actual file
	var fileStream:FileStream = new FileStream(); // Create our file stream
	fileStream.open(mySettings, FileMode.READ);
	var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable); // Read the contens of the file
	var slines:Array=fileContents.split('\n');
	var i:int;
	for(i=0;i<slines.length;i++){
		switch(i){
			case 0:
				username.text=slines[0].toString().split("=")[1];
				break;
			case 1:
				password.text=slines[1].toString().split("=")[1];
				break;
			case 2:
				logpath.text=slines[2].toString().split("=")[1];
				break;
			case 3:
				dellog=slines[3].toString().split("=")[1];
				if(dellog.match("True")) deletelogfile.selected=true;
				break;
			case 4:
				exitapp=slines[4].toString().split("=")[1];
				if(exitapp.match("True")) exitafter.selected=true;
				break;
			case 5:
				savepass=slines[5].toString().split("=")[1];
				if(savepass.match("True")) savepasswd.selected=true;
				break;
			case 6:
				fix=slines[6].toString().split("=")[1];
				if(fix.match("True")) fixtime.selected=true;
				break;
		}
	}
	fileStream.close(); // Clean up and close the file stream
}

public var lines:Array=new Array();
public var tracks:Array=new Array();
public function parseFile():void{
	var dp:Array = new Array();
	trackdata.dataProvider=null;
	var myFile:File = File.applicationDirectory;
	myFile = myFile.resolvePath(".scrobbler.log"); // Point it to an actual file
	var fileStream:FileStream = new FileStream(); // Create our file stream
	fileStream.open(myFile, FileMode.READ);
	var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable); // Read the contens of the file
	var lines:Array=fileContents.split('\n');
	var i:int;
	for(i=0;i<lines.length;i++){
		var tracks:Array=lines[i].split('\t');
		if(tracks[0] && tracks[2] && tracks[3] && tracks[5] == "L" && tracks[6]){
			dp.push({artist:tracks[0],album:tracks[1],trackname:tracks[2],tracknumber:tracks[3],length:tracks[4],timestamp:tracks[6]});
		}
	}
	fileStream.close(); // Clean up and close the file stream
	trackdata.dataProvider=dp;
}

public function showLastPlayed():void{
	lasttenitems.dataProvider=null;
	lastten.visible=true;
	getLastPlayed.send();
}

public function browseLog():void{
	
}



public var sessionstatus:String=null;
public var session:WMFScrobbler=new WMFScrobbler();
public var sesstimer:Timer=new Timer(250);
public function uploadLog():void{
	handshake();
}

public function handshake():void{
	//Begin Handshake
	session.username=username.text;
	session.password=password.text;
	session.handshake();
	sesstimer.addEventListener(TimerEvent.TIMER,getHSStatus);
	sesstimer.start()
}

public function getHSStatus(event:TimerEvent):void{
	sessionstatus=session.handshakeStatus()
	if(sessionstatus){
		sesstimer.stop();
	}
	switch(sessionstatus){
		case "OK":
			processTracks();
			break;
		case "BANNED":
			Alert.show('This client AIRScrobbler Version: ' + AIRScrobblerVersion + ' may have been banned please check for a new version, or contact the author.');
			break;
		case "BADAUTH":
			Alert.show('Authorization failed, please check your username and password');
			break;
		case "BADTIME":
			Alert.show('Bad timestamp, this may be a bug in the application, please contact the author if this error continually occurs.');
			break;
		default:
			break;
	}
}

private var _selectedValue:String;
public function processTracks():void{
	for (var i:int=0;i<trackdata.dataProvider.length;i++){
		for(var k:int=0; k < trackdata.columns.length; k++) {
			var artist:String=trackdata.dataProvider.getItemAt(i)[trackdata.columns[1].dataField];
			var album:String=trackdata.dataProvider.getItemAt(i)[trackdata.columns[2].dataField];
			var tracknumber:String=trackdata.dataProvider.getItemAt(i)[trackdata.columns[3].dataField];
			var trackname:String=trackdata.dataProvider.getItemAt(i)[trackdata.columns[4].dataField];
			var length:String=trackdata.dataProvider.getItemAt(i)[trackdata.columns[5].dataField];
			var timestamp:String=trackdata.dataProvider.getItemAt(i)[trackdata.columns[6].dataField];
		}
		Alert.show(artist+ ' ' + album + ' ' + tracknumber + ' ' + trackname + ' ' + length + ' ' + timestamp);
	}
	//session.scrobbleThis('Built To Spill','Twin Falls','1185039240','320','2','Theres Nothing Wrong With Love');
}

public function goProfile():void{
	navigateToURL(new URLRequest(lastfmurl.label), 'quote');
}

public function saveSettings():void{
	
}
public function updateURL():void{
	lastfmurl.label='http://www.last.fm/user/'+username.text;
}
public function showTrackSelection():void{
	if(selecteachtrack.selected==true){
		Application.application.height=700;
		selecttracks.height=450;
		trackdata.visible=true;
	} else {
		Application.application.height=340;
		selecttracks.height=71;
		trackdata.visible=false;
	}
}